﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using Xenta.Utils;
using Xenta.Attributes;

namespace Xenta.Web.Controllers
{
    public sealed class AccessController : ExtController
    {
        #region GET/POST Actions

        [HttpGet, RestoreState]
        public ActionResult SignIn()
        {
            ViewBag.SignInForm_Email = TempData.RestoreObject<String>("SignInForm_Email");

            return View();
        }

        [HttpPost, PersistState]
        public ActionResult SignIn(string email, string password, string returnUrl)
        {
            email = StringHelper.EnsureNotNull(email).TrimToLen(100);
            password = StringHelper.EnsureNotNull(password).TrimToLen(100);

            try
            {
                var m = Svc.ProcessOperation("OpenSession", new
                {
                    Identity = email,
                    Password = password,
                    Source = HttpContext.Request.GetUserHostAddress()
                }, new
                {
                    DisclosureLevel = "Keys"
                });

                FormsAuthentication.SetAuthCookie(JDM.String(m.Guid), true);

                if(!String.IsNullOrWhiteSpace(returnUrl))
                    return Redirect(returnUrl);
                return RedirectToAction(Loc.Act("Home").Ctrl("Static"));
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
                TempData.PersistObject("SignInForm_Email", email);
            }
            return RedirectToAction(Loc.Act("SignIn"));
        }

        [HttpGet, Authenticate]
        public ActionResult SignOut()
        {
            if(Svc.IsAuthenticated)
            {
                Svc.ProcessOperation("CloseSession", new
                {
                    EntityID = JDM.Int32(Svc.Session.EntityID)
                });
                FormsAuthentication.SignOut();
            }
            return RedirectToAction(Loc.Act("SignIn"));
        }

        #endregion
    }
}
